package com.mapproject.industrymap.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Component
public class DataPgdump {
    public  ReturnValue impshpdata(String filepath,String tablename){
        try {
            String filedir=filepath;
            List<String> cmdList = new ArrayList<>();
            cmdList.add("cmd");
            cmdList.add("/c");
            cmdList.add("F: & cd PostgreSQL\\13\\bin & shp2pgsql -D -c -W \"GBK\" "+filedir+" "+tablename+" industrymap|psql -d industrymap -U postgres");
            ProcessBuilder pb = new ProcessBuilder(cmdList);
            Map<String,String> env=pb.environment();
            env.put("PGPASSWORD","postgres");
            pb.redirectErrorStream(true);
            Process process = pb.start();
            readProcessOutput(process.getInputStream(), System.out);
            int state = process.exitValue();
//            System.out.println(state);
//            System.out.println("ok");
            return new ReturnValue(200,"入库成功",state);

        } catch (IOException e) {
            // TODO Auto-generated catch block

            return new ReturnValue(500,"入库失败",e);

        }



    }
    private static void readProcessOutput(InputStream inputStream, PrintStream out) {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("GBK")));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            System.out.println("-end");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
